package felix.rule.data.config;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.postgresql.util.PGobject;
import org.springframework.stereotype.Component;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * json格式的字段，进行转换的自定义转换器，转换为实体类的JsonNode属性
 */
@MappedTypes(JsonNode.class)
@MappedJdbcTypes(JdbcType.JAVA_OBJECT)
@Component
public class JsonHandler extends BaseTypeHandler<JsonNode> {

    private final ObjectMapper mapper = new ObjectMapper();

    private static final String POSTGRES = "PostgreSQL";
    private static final PGobject JSON_OBJECT = new PGobject();


    /**
     * 设置非空参数
     */
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, JsonNode parameter, JdbcType jdbcType) throws SQLException {
        if (POSTGRES.equals(ps.getConnection().getMetaData().getDatabaseProductName())) {
            JSON_OBJECT.setType("jsonb");
            JSON_OBJECT.setValue(parameter.toString());
            ps.setObject(i, JSON_OBJECT);
        } else {
            ps.setString(i, parameter.toString());
        }
    }

    /**
     * 根据列名，获取可以为空的结果
     */
    @Override
    public JsonNode getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String sqlJson = rs.getString(columnName);
        if (null != sqlJson) {
            try {
                return mapper.readTree(sqlJson);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
                return null;
            }
        }
        return null;
    }

    /**
     * 根据列索引，获取可以为空的结果
     */
    @Override
    public JsonNode getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String sqlJson = rs.getString(columnIndex);
        if (null != sqlJson) {
            try {
                return mapper.readTree(sqlJson);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
                return null;
            }
        }
        return null;
    }

    @Override
    public JsonNode getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String sqlJson = cs.getString(columnIndex);
        if (null != sqlJson) {
            try {
                return mapper.readTree(sqlJson);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
                return null;
            }
        }
        return null;
    }
}
